package com.code.utils;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import com.code.entity.ColumnEntity;
import com.code.entity.TableEntity;

import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器 工具类
 * 
 * @author hyl
 * @date 2019/1/11
 */
public class GenUtils {

	public static List<String> getTemplates() {
		List<String> templates = new ArrayList<String>();
		templates.add("template/Entity.java.vm");
		templates.add("template/Mapper.java.vm");
		templates.add("template/Mapper.xml.vm");
		templates.add("template/Service.java.vm");
		templates.add("template/ServiceImpl.java.vm");
		//templates.add("template/Controller.java.vm");
		templates.add("template/Query.java.vm");
		templates.add("template/Form.java.vm");
		// templates.add("template/list.html.vm");
		// templates.add("template/list.js.vm");
		// templates.add("template/menu.sql.vm");
		return templates;
	}

	/**
	 * 生成代码
	 */
	public static void generatorCode(Map<String, String> table, List<Map<String, String>> columns) {
		generatorCode(null, null, null, table, columns,null);
	}

	public static void generatorCode(String mainPath, String moduleName, String packageName, Map<String, String> table,
			List<Map<String, String>> columns, ZipOutputStream zip) {
		Configuration config = getConfig();

		boolean hasBigDecimal = false;
		// 表信息
		TableEntity tableEntity = new TableEntity();
		tableEntity.setTableName(table.get("tableName"));
		tableEntity.setComments(table.get("tableComment"));
		// 表名转换成Java类名
		String className = tableToJava(tableEntity.getTableName(), config.getString("tablePrefix"));
		tableEntity.setClassName(className);
		tableEntity.setClassname(StringUtils.uncapitalize(className));

		// 列信息
		List<ColumnEntity> columsList = new ArrayList<>();
		for (Map<String, String> column : columns) {
			ColumnEntity columnEntity = new ColumnEntity();
			columnEntity.setColumnName(column.get("columnName"));
			columnEntity.setDataType(column.get("dataType"));
			columnEntity.setComments(column.get("columnComment"));
			columnEntity.setExtra(column.get("extra"));

			// 列名转换成Java属性名
			String attrName = columnToJava(columnEntity.getColumnName());
			columnEntity.setAttrName(attrName);
			columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

			// 列的数据类型，转换成Java类型
			String attrType = config.getString(columnEntity.getDataType(), "unknowType");
			columnEntity.setAttrType(attrType);
			if (!hasBigDecimal && attrType.equals("BigDecimal")) {
				hasBigDecimal = true;
			}
			// 是否主键
			if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
				tableEntity.setPk(columnEntity);
			}

			columsList.add(columnEntity);
		}
		tableEntity.setColumns(columsList);

		// 没主键，则第一个字段为主键
		if (tableEntity.getPk() == null) {
			tableEntity.setPk(tableEntity.getColumns().get(0));
		}

		// 设置velocity资源加载器
		Properties prop = new Properties();
		prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		Velocity.init(prop);

		// 封装模板数据
		Map<String, Object> map = new HashMap<>();
		map.put("tableName", tableEntity.getTableName());
		map.put("comments", tableEntity.getComments());
		map.put("pk", tableEntity.getPk());
		map.put("className", tableEntity.getClassName());
		map.put("classname", tableEntity.getClassname());
		map.put("pathName", tableEntity.getClassname().toLowerCase());
		map.put("columns", tableEntity.getColumns());
		map.put("hasBigDecimal", hasBigDecimal);
		map.put("mainPath", (mainPath == null||"null".equals(mainPath)) ? config.getString("mainPath") : mainPath);
		map.put("package", (packageName == null||"null".equals(packageName)) ? config.getString("package") :packageName);
		map.put("moduleName", (moduleName == null||"null".equals(moduleName)) ? config.getString("moduleName") : moduleName);
		map.put("author", config.getString("author"));
		map.put("email", config.getString("email"));
		map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
		VelocityContext context = new VelocityContext(map);

		// 获取模板列表
		List<String> templates = getTemplates();
		for (String template : templates) {
			// 渲染模板
			StringWriter sw = new StringWriter();
			Template tpl = Velocity.getTemplate(template, "UTF-8");
			tpl.merge(context, sw);

			try {
				// 添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassName(),
                        packageName == null ? config.getString("package") : packageName,
                        moduleName == null ? config.getString("moduleName") : moduleName)));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
			/*	String fliePath =map.get("mainPath")+File.separator+getFileName(template, tableEntity.getClassName(),map.get("package").toString(),
						map.get("moduleName").toString());
				writeFile(sw.toString().getBytes(),fliePath);*/
			} catch (IOException e) {
				e.printStackTrace();
				throw new CustomException("渲染模板失败，表名：" + tableEntity.getTableName(), e);
			}
		}
	}

	/**
	 * 列名转换成Java属性名
	 */
	public static String columnToJava(String columnName) {
		return WordUtils.capitalizeFully(columnName, new char[] { '_' }).replace("_", "");
	}

	/**
	 * 表名转换成Java类名
	 */
	public static String tableToJava(String tableName, String tablePrefix) {
		if (StringUtils.isNotBlank(tablePrefix)) {
			tableName = tableName.replace(tablePrefix, "");
		}
		 String result = columnToJava(tableName);
		 return result;
		//return result.substring(2,result.length());
	}

	/**
	 * 获取配置信息
	 */
	public static Configuration getConfig() {
		try {
			return new PropertiesConfiguration("generator.properties");
		} catch (ConfigurationException e) {
			throw new CustomException("获取配置文件失败，", e);
		}
	}

	/**
	 * 获取文件名
	 */
	public static String getFileName(String template, String className, String packageName, String moduleName) {
		String packagePath = "src"+File.separator+"main" + File.separator + "java" + File.separator;
		if (StringUtils.isNotBlank(packageName)) {
			packagePath += packageName.replace(".", File.separator) + File.separator;
		}
		if (template.contains("Entity.java.vm")) {
			if(StringUtils.isNotBlank(moduleName)&&!"null".equals(moduleName)) {
				return packagePath +"dal"+  File.separator+"entity" + File.separator +moduleName + File.separator+ className + ".java";
			}
			return packagePath + "dal"+  File.separator+ "entity" + File.separator + className + ".java";
		}
		if (template.contains("Query.java.vm")) {
			if(StringUtils.isNotBlank(moduleName)&&!"null".equals(moduleName)) {
				return packagePath+  "query" + File.separator +moduleName + File.separator+ className + "Query.java";
			}
			return packagePath +  "query" + File.separator + className + "Query.java";
		}
		if (template.contains("Form.java.vm")) {
			if(StringUtils.isNotBlank(moduleName)&&!"null".equals(moduleName)) {
				return packagePath+  "form" + File.separator +moduleName + File.separator+ className + "Form.java";
			}
			return packagePath + "form" + File.separator + className + "Form.java";
		}

		if (template.contains("Mapper.java.vm")) {
			if(StringUtils.isNotBlank(moduleName)&&!"null".equals(moduleName)) {
				return packagePath + "mapper" + File.separator +moduleName + File.separator+ className + "Mapper.java";
			}
			return packagePath + "mapper" + File.separator + className + "Mapper.java";
		}

		if (template.contains("Service.java.vm")) {
			if(StringUtils.isNotBlank(moduleName)&&!"null".equals(moduleName)) {
				return packagePath + "service" + File.separator +moduleName + File.separator+ className + "Service.java";
			}
			return packagePath + "service" + File.separator + className + "Service.java";
		}

		if (template.contains("ServiceImpl.java.vm")) {
			if(StringUtils.isNotBlank(moduleName)&&!"null".equals(moduleName)) {
				return packagePath + "service" + File.separator + "impl" + File.separator +moduleName + File.separator+ className + "ServiceImpl.java";
			}
			return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
		}

		if (template.contains("Controller.java.vm")) {
			if(StringUtils.isNotBlank(moduleName)&&!"null".equals(moduleName)) {
				return packagePath + "controller" + File.separator +moduleName + File.separator+ className + "Controller.java";
			}
			return packagePath + "controller" + File.separator + className + "Controller.java";
		}

		if (template.contains("Mapper.xml.vm")) {
			if(StringUtils.isNotBlank(moduleName)){
				return "src"+File.separator+"main" + File.separator + "resources" + File.separator + "mapper" + File.separator + moduleName
						+ File.separator + className + "Mapper.xml";
			}else{
				return "src"+File.separator+"main" + File.separator + "resources" + File.separator + "mapper" + File.separator
						+ className + "Mapper.xml";
			}

		}

		if (template.contains("list.html.vm")) {
			if(StringUtils.isNotBlank(moduleName)&&!"null".equals(moduleName)){
				return "src"+File.separator+"main" + File.separator + "resources" + File.separator + "templates" + File.separator + "modules"
						+ File.separator + moduleName + File.separator + className.toLowerCase() + ".html";
			}else{
				return "src"+File.separator+"main" + File.separator + "resources" + File.separator + "templates" + File.separator
						 + className.toLowerCase() + ".html";
			}

		}

		if (template.contains("list.js.vm")) {
			if(StringUtils.isNotBlank(moduleName)&&!"null".equals(moduleName)){
				return "src"+File.separator+"main" + File.separator + "resources" + File.separator + "statics" + File.separator + "js"
						+ File.separator + "modules" + File.separator + moduleName + File.separator
						+ className.toLowerCase() + ".js";
			}else{
				return "src"+File.separator+"main" + File.separator + "resources" + File.separator + "statics" + File.separator + "js"
						+ File.separator + className.toLowerCase() + ".js";
			}

		}

		if (template.contains("menu.sql.vm")) {
			return className.toLowerCase() + "_menu.sql";
		}

		return null;
	}

	private static void writeFile(byte [] data,String  fliePath)throws IOException{

       //取到跟目录
		Configuration config = getConfig();
		String  rootPath =  config.getString("rootPath");
		//判断是否创建目录
		fliePath = rootPath+ File.separator+fliePath;
		int start = fliePath.lastIndexOf(File.separator);
		String fileDir = fliePath.substring(0,start);
		File dir = new File(fileDir);
		//判断文件目录是否存在
		if(!dir.exists()){
			//创建文件夹
			dir.mkdirs();
		}
		//判断是重新生成代码
		Boolean  overwrite =  config.getBoolean("overwrite");
		//不需要重生成 去检验之前的文件出在不   存在直接结束掉
		if(!overwrite){
			File file2=new File(fliePath);
			if (file2.exists()) {
				return;
			}
		}
		File file = new File(fliePath);
		FileOutputStream  fos = new FileOutputStream(file);
		BufferedOutputStream  bos = new BufferedOutputStream(fos);
		bos.write(data);
		bos.close();
		fos.close();
	}

}
